package com.woniu.houtai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.houtai.entity.Business;
import com.woniu.houtai.entity.Comment;
import com.woniu.houtai.entity.Shop;
import com.woniu.houtai.mapper.CommentMapper;
import com.woniu.houtai.service.BusinessService;
import com.woniu.houtai.service.CommentService;
import com.woniu.houtai.service.ShopService;
import com.woniu.houtai.utils.CookieUtils;
import com.woniu.houtai.utils.JwtUtils;
import com.woniu.houtai.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author firstGroup
 * @since 2023-02-22 09:45:58
 */
@Controller
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentService commentService;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    BusinessService businessService;
    @Autowired
    ShopService shopService;
    @RequestMapping("/userComments")
    @ResponseBody
    public Page<CommentVo> userComments(Integer currentPage,Integer pageSize,Integer shopId){
        Page<CommentVo> commentVoPage = commentService.queryCommentsAndDetails(currentPage,pageSize,shopId);
        return commentVoPage ;
    }
    private Business getCurrentBusiness(HttpServletRequest request) {
        //获取已登录商家信息
        // 1.先从request中拿到token
        // 2.从token中获取用户名
        // 3.根据用户名查询到用户信息
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        return businessService.getBusinessByName(account);
    }

    @RequestMapping("/test")
    @ResponseBody
    public Page<Comment> test(Integer currentPage,Integer pageSize,Integer shopId){
        Page<Comment> commentPage = new Page<>(currentPage,pageSize);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        Page<Comment> page = commentMapper.selectPage(commentPage,queryWrapper);
        return page;
    }


    @RequestMapping("/grade")
    @ResponseBody
    public double selectAll(Integer shopId){
        List<Comment> comments = commentService.queryComments(shopId);
        Double grade = new Double(0.00);
        for (Comment comment : comments) {
           grade = grade + comment.getGrade();
        }

        System.out.println(grade/comments.size());
        return grade/comments.size();
    }
    @RequestMapping("/reply")
    @ResponseBody
    public String reply(Integer commentId,String reply){
        int i = commentService.updatrToReply(commentId, reply);
        return "ok";
    }




}

